package com.example.blockbreaker;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.view.HapticFeedbackConstants;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;

import androidx.fragment.app.Fragment;

import com.google.android.material.button.MaterialButton;
import com.google.android.material.slider.Slider;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.textfield.TextInputEditText;

public class HealthFragment extends Fragment {
    private MaterialButton btnSave;
    private Slider sliderEnergy, sliderCraving;
    private TextInputEditText etHeartRate, etOxygenLevel;
    private HealthDataRepository repository;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_health, container, false);

        // 初始化视图组件
        btnSave = view.findViewById(R.id.btn_save);
        sliderEnergy = view.findViewById(R.id.slider_energy);
        sliderCraving = view.findViewById(R.id.slider_craving);
        etHeartRate = view.findViewById(R.id.et_heart_rate);
        etOxygenLevel = view.findViewById(R.id.et_oxygen_level);

        // 初始化Repository
        repository = new HealthDataRepository(requireActivity().getApplication());

        setupSaveButton();

        return view;
    }

    private void setupSaveButton() {
        btnSave.setOnClickListener(v -> {
            // 1. 提供触觉反馈
            provideHapticFeedback();

            // 2. 验证输入
            if (!validateInput()) {
                return;
            }

            // 3. 收集数据
            HealthData healthData = collectHealthData();

            // 4. 保存数据
            saveHealthData(healthData);

            // 5. 显示反馈
            showSaveConfirmation(healthData);

            // 6. 重置表单(可选)
            resetForm();
        });
    }

    private void provideHapticFeedback() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            btnSave.performHapticFeedback(HapticFeedbackConstants.CONFIRM);
        } else {
            btnSave.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
        }
    }

    private boolean validateInput() {
        // 验证心率输入
        String heartRateStr = etHeartRate.getText().toString().trim();
        if (!heartRateStr.isEmpty()) {
            try {
                int heartRate = Integer.parseInt(heartRateStr);
                if (heartRate < 40 || heartRate > 200) {
                    etHeartRate.setError("请输入有效心率(40-200)");
                    return false;
                }
            } catch (NumberFormatException e) {
                etHeartRate.setError("请输入数字");
                return false;
            }
        }

        // 验证血氧输入
        String oxygenStr = etOxygenLevel.getText().toString().trim();
        if (!oxygenStr.isEmpty()) {
            try {
                int oxygen = Integer.parseInt(oxygenStr);
                if (oxygen < 70 || oxygen > 100) {
                    etOxygenLevel.setError("请输入有效血氧值(70-100)");
                    return false;
                }
            } catch (NumberFormatException e) {
                etOxygenLevel.setError("请输入数字");
                return false;
            }
        }

        return true;
    }

    private HealthData collectHealthData() {
        // 获取当前时间戳
        long timestamp = System.currentTimeMillis();

        // 解析心率(可为null)
        Integer heartRate = null;
        try {
            heartRate = Integer.parseInt(etHeartRate.getText().toString().trim());
        } catch (NumberFormatException e) {
            // 保持为null
        }

        // 解析血氧(可为null)
        Integer oxygenLevel = null;
        try {
            oxygenLevel = Integer.parseInt(etOxygenLevel.getText().toString().trim());
        } catch (NumberFormatException e) {
            // 保持为null
        }

        // 获取滑块值
        int energyLevel = (int) sliderEnergy.getValue();
        int cravingIntensity = (int) sliderCraving.getValue();

        return new HealthData(
                timestamp,
                heartRate,
                oxygenLevel,
                energyLevel,
                cravingIntensity
        );
    }

    private void saveHealthData(HealthData healthData) {
        // 保存到数据库
        repository.insert(healthData);

        // 更新本地SharedPreferences(可选)
        updateHealthStats(healthData);
    }

    private void updateHealthStats(HealthData healthData) {
        SharedPreferences prefs = requireActivity().getSharedPreferences("HealthPrefs", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();

        // 更新最新记录
        if (healthData.getHeartRate() != null) {
            editor.putInt("last_heart_rate", healthData.getHeartRate());
        }
        if (healthData.getOxygenLevel() != null) {
            editor.putInt("last_oxygen_level", healthData.getOxygenLevel());
        }
        editor.putInt("last_energy_level", healthData.getEnergyLevel());
        editor.putInt("last_craving_intensity", healthData.getCravingIntensity());

        // 更新统计数据
        int totalRecords = prefs.getInt("total_health_records", 0) + 1;
        editor.putInt("total_health_records", totalRecords);

        editor.apply();
    }

    private void showSaveConfirmation(HealthData healthData) {
        String message = "健康数据已保存！";

        // 根据数据提供个性化反馈
        if (healthData.getEnergyLevel() < 4) {
            message += "\n您的能量水平较低，建议休息";
        }
        if (healthData.getCravingIntensity() >= 7) {
            message += "\n检测到强烈烟瘾，试试深呼吸练习";
        }

        // 使用Snackbar显示
        Snackbar snackbar = Snackbar.make(
                requireView(),
                message,
                Snackbar.LENGTH_LONG
        );

        // 为高烟瘾强度添加快速操作
        if (healthData.getCravingIntensity() >= 7) {
            snackbar.setAction("开始练习", v -> {
                startActivity(new Intent(requireActivity(), BreathingActivity.class));
            });
        }

        snackbar.show();
    }

    private void resetForm() {
        // 重置滑块到中间位置
        sliderEnergy.setValue(5f);
        sliderCraving.setValue(5f);

        // 清空输入框
        etHeartRate.setText("");
        etOxygenLevel.setText("");
        etHeartRate.clearFocus();
        etOxygenLevel.clearFocus();

        // 隐藏键盘
        InputMethodManager imm = (InputMethodManager) requireActivity()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(etHeartRate.getWindowToken(), 0);
    }
}